package com.easemob.util;

import android.content.Context;
import android.os.Build.VERSION;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import com.easemob.chat.EMChatConfig;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class FileLogger
{
  private static final String TAG = "FileLogger";
  private static final long MB = 1048576L;
  private static final long LOG_LIMIT = 8388608L;
  private static final long FREE_SPACE_LIMIT = 20971520L;
  private static final long FREE_SPACE_TIMER = 1200000L;
  private static final String INFO_COLOR = "green";
  private static final String ERROR_COLOR = "red";
  private static final String WARN_COLOR = "orange";
  private static final String DEBUG_COLOR = "blue";
  private ExecutorService singleThreadService = Executors.newSingleThreadExecutor();
  private File logRoot = null;
  private Timer timer = null;
  private boolean spaceAvailable = true;

  void d(String paramString1, String paramString2)
  {
    startThreadService("blue", "[" + paramString1 + "]" + paramString2);
  }

  void e(String paramString1, String paramString2)
  {
    startThreadService("red", "[" + paramString1 + "]" + "[ERROR]" + paramString2);
  }

  void i(String paramString1, String paramString2)
  {
    startThreadService("green", "[" + paramString1 + "]" + paramString2);
  }

  void w(String paramString1, String paramString2)
  {
    startThreadService("orange", "[" + paramString1 + "]" + "[WARN]" + paramString2);
  }

  void v(String paramString1, String paramString2)
  {
    startThreadService("green", "[" + paramString1 + "]" + paramString2);
  }

  private void startThreadService(String paramString1, String paramString2)
  {
    File localFile = getLogRoot();
    if ((localFile == null) || (!localFile.exists()))
      return;
    this.singleThreadService.execute(getWriterRunnable(paramString1, paramString2));
  }

  private Runnable getWriterRunnable(final String paramString1, final String paramString2)
  {
    return new Runnable()
    {
      public void run()
      {
        try
        {
          File localFile1 = FileLogger.this.getLogRoot();
          if ((localFile1 == null) || (!localFile1.exists()))
            return;
          if ((FileLogger.this.timer == null) && (!FileLogger.this.freeSpace()))
            return;
          FileLogger.this.startCleanUpTimer();
          File localFile2 = FileLogger.this.getAvailableFile();
          if (localFile2 == null)
            return;
          int i = 0;
          if (!localFile2.exists())
            try
            {
              localFile2.createNewFile();
              i = 1;
            }
            catch (IOException localIOException1)
            {
              localIOException1.printStackTrace();
            }
          if (!localFile2.exists())
            return;
          FileOutputStream localFileOutputStream = null;
          try
          {
            localFileOutputStream = new FileOutputStream(localFile2, true);
            if (i != 0)
            {
              localObject1 = "<header>";
              localObject1 = localObject1 + "<meta http-equiv=" + "\"" + "Content-Type" + "\"" + " content=" + "\"" + "text/html; charset=UTF-8" + "\">";
              localObject1 = localObject1 + "</header>";
              localFileOutputStream.write(((String)localObject1).getBytes());
            }
            Object localObject1 = new Date();
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String str1 = localSimpleDateFormat.format((Date)localObject1);
            String str2 = paramString2.replaceAll(">", "&gt;");
            str2 = str2.replaceAll("<", "&lt;");
            String str3 = "<p><font color =\"" + paramString1 + "\">" + str1 + " " + str2 + "</p>";
            byte[] arrayOfByte = str3.getBytes();
            localFileOutputStream.write(arrayOfByte);
          }
          catch (FileNotFoundException localFileNotFoundException)
          {
            localFileNotFoundException.printStackTrace();
            try
            {
              if (localFileOutputStream == null)
                return;
              localFileOutputStream.close();
            }
            catch (IOException localIOException3)
            {
              localIOException3.printStackTrace();
            }
          }
          catch (IOException localIOException2)
          {
            localIOException2.printStackTrace();
            try
            {
              if (localFileOutputStream == null)
                return;
              localFileOutputStream.close();
            }
            catch (IOException localIOException4)
            {
              localIOException4.printStackTrace();
            }
          }
          finally
          {
            try
            {
              if (localFileOutputStream != null)
                localFileOutputStream.close();
            }
            catch (IOException localIOException5)
            {
              localIOException5.printStackTrace();
            }
          }
          try
          {
            if (localFileOutputStream != null)
              localFileOutputStream.close();
          }
          catch (IOException localIOException6)
          {
            localIOException6.printStackTrace();
          }
        }
        catch (NullPointerException localNullPointerException)
        {
          localNullPointerException.printStackTrace();
          Log.e("FileLogger", localNullPointerException.getMessage());
        }
        catch (Exception localException)
        {
          localException.printStackTrace();
          Log.e("FileLogger", localException.getMessage());
        }
      }
    };
  }

  private File getAvailableFile()
  {
    File localFile1 = getLogRoot();
    if ((localFile1 == null) || (!localFile1.exists()))
      return null;
    Date localDate = new Date();
    SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String str1 = localSimpleDateFormat.format(localDate);
    removeOldFolders();
    File localFile2 = getLogFolder();
    int i = 0;
    List localList = null;
    File[] arrayOfFile = localFile2.listFiles();
    if ((arrayOfFile != null) && (arrayOfFile.length > 0))
    {
      localList = Arrays.asList(arrayOfFile);
      if (localList.size() > 1)
      {
        getSortedFileListByName(localList);
        arrayOfFile = (File[])localList.toArray();
      }
      str2 = arrayOfFile[0].getName();
      str2 = str2.substring(0, str2.indexOf("."));
      try
      {
        i = Integer.parseInt(str2);
      }
      catch (Exception localException)
      {
        localException.printStackTrace();
        Log.e("FileLogger", "Wrong cntName! : " + str2);
      }
      if (arrayOfFile[0].length() >= 1048576L)
        i++;
    }
    String str2 = getLogFileName(i);
    return new File(localFile2, str2);
  }

  private static String getLogFileName(int paramInt)
  {
    String str1 = String.valueOf(paramInt);
    String str2 = "000";
    String str3 = str2.substring(str1.length());
    str3 = str3 + str1 + ".html";
    return str3;
  }

  private File getLogFolder()
  {
    Date localDate = new Date();
    SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String str = localSimpleDateFormat.format(localDate);
    File localFile1 = getLogRoot();
    File localFile2 = new File(localFile1, str);
    if (!localFile2.exists())
      localFile2.mkdirs();
    return localFile2;
  }

  private void removeFolderBeforeDay(String paramString, int paramInt)
  {
    String str = getSpecifiedDayBefore(paramString, paramInt);
    File localFile1 = getLogRoot();
    File localFile2 = new File(localFile1, str);
    if (localFile2.exists())
      deleteFile(localFile2);
  }

  private void removeOldFolders()
  {
    File localFile1 = getLogRoot();
    if ((localFile1 == null) || (!localFile1.exists()))
      return;
    Date localDate = new Date();
    SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String str1 = localSimpleDateFormat.format(localDate);
    String str2 = getSpecifiedDayBefore(str1, 1);
    File[] arrayOfFile1 = localFile1.listFiles();
    if (arrayOfFile1 == null)
      return;
    for (File localFile2 : arrayOfFile1)
      if ((localFile2.isDirectory()) && (!localFile2.getName().contains(str1)) && (!localFile2.getName().contains(str2)))
        deleteFile(localFile2);
      else
        localFile2.delete();
  }

  private static void deleteFile(File paramFile)
  {
    if (paramFile == null)
      return;
    if (paramFile.exists())
      if (paramFile.isDirectory())
      {
        File[] arrayOfFile1 = paramFile.listFiles();
        if (arrayOfFile1 != null)
          for (File localFile : arrayOfFile1)
            deleteFile(localFile);
        paramFile.delete();
      }
      else
      {
        paramFile.delete();
      }
  }

  private static long getDirSize(File paramFile)
  {
    if (paramFile == null)
      return 0L;
    if (paramFile.isDirectory())
    {
      long l = 0L;
      File[] arrayOfFile1 = paramFile.listFiles();
      if (arrayOfFile1 != null)
        for (File localFile : arrayOfFile1)
          l += getDirSize(localFile);
      return l;
    }
    return paramFile.length();
  }

  private static String getSpecifiedDayBefore(String paramString, int paramInt)
  {
    Calendar localCalendar = Calendar.getInstance();
    Date localDate = null;
    try
    {
      localDate = new SimpleDateFormat("yyyyMMdd").parse(paramString);
    }
    catch (ParseException localParseException)
    {
      localParseException.printStackTrace();
    }
    localCalendar.setTime(localDate);
    int i = localCalendar.get(5);
    localCalendar.set(5, i - paramInt);
    String str = new SimpleDateFormat("yyyyMMdd").format(localCalendar.getTime());
    return str;
  }

  private static File getStorageDir()
  {
    if (Environment.getExternalStorageState().equals("mounted"))
      return Environment.getExternalStorageDirectory();
    return Environment.getDataDirectory();
  }

  private static void getSortedFileListByName(List<File> paramList)
  {
    Collections.sort(paramList, new Comparator()
    {
      public int compare(File paramAnonymousFile1, File paramAnonymousFile2)
      {
        return paramAnonymousFile2.getName().compareTo(paramAnonymousFile1.getName());
      }
    });
  }

  private boolean spaceIsAlearting()
  {
    long l = getCurrentAvailabeSpace();
    return l < 20971520L;
  }

  private boolean logSizeAlearting()
  {
    long l = getDirSize(getLogRoot());
    return l > 8388608L;
  }

  boolean freeSpace()
  {
    File localFile = getLogRoot();
    if ((localFile == null) || (!localFile.exists()))
      return false;
    if (spaceIsAlearting())
    {
      Log.w("FileLogger", "there is no availabe free space and try to free space");
      freeLogFolder();
      return !spaceIsAlearting();
    }
    checkAndFreeLogFiles();
    return true;
  }

  private void freeLogFolder()
  {
    deleteFile(getLogRoot());
  }

  private void freeOldFolders()
  {
    Date localDate = new Date();
    SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String str = localSimpleDateFormat.format(localDate);
    File[] arrayOfFile1 = getLogRoot().listFiles();
    for (File localFile : arrayOfFile1)
      if ((localFile.isDirectory()) && (!localFile.getName().contains(str)))
        deleteFile(localFile);
      else
        localFile.delete();
  }

  private void freeOldFiles()
  {
    File[] arrayOfFile = getLogFolder().listFiles();
    if (arrayOfFile != null)
    {
      List localList = Arrays.asList(arrayOfFile);
      getSortedFileListByName(localList);
      if (localList.size() > 5)
      {
        int i = localList.size();
        for (int j = 5; j < i; j++)
        {
          Log.w("FileLogger", "try to delete file : " + ((File)localList.get(j)).getAbsoluteFile());
          ((File)localList.get(j)).delete();
        }
      }
    }
  }

  private static long getCurrentAvailabeSpace()
  {
    StatFs localStatFs = new StatFs(getStorageDir().getPath());
    if (Build.VERSION.SDK_INT >= 18)
      return localStatFs.getAvailableBytes();
    long l1 = localStatFs.getAvailableBlocks();
    long l2 = localStatFs.getBlockSize();
    return l1 * l2;
  }

  File getLogRoot()
  {
    String str1 = EMChatConfig.getInstance().APPKEY;
    Context localContext = EMChatConfig.getInstance().getApplicationContext();
    String str2 = "/Android/data/";
    if (localContext != null)
      str2 = str2 + localContext.getPackageName();
    if (str1 == null)
      return null;
    str2 = str2 + "/" + str1 + "/log/";
    File localFile = new File(getStorageDir(), str2);
    synchronized (this)
    {
      if (!localFile.exists())
        localFile.mkdirs();
    }
    return localFile;
  }

  void checkAndFreeLogFiles()
  {
    if (logSizeAlearting())
    {
      Log.w("FileLogger", "the log size is > 8M, try to free log files");
      freeOldFolders();
      Log.w("FileLogger", "old folders are deleted");
      if (logSizeAlearting())
      {
        Log.w("FileLogger", "try to delete old log files");
        freeOldFiles();
      }
    }
  }

  private void startCleanUpTimer()
  {
    synchronized (this)
    {
      if (this.timer == null)
      {
        this.timer = new Timer();
        TimerTask local3 = new TimerTask()
        {
          public void run()
          {
            FileLogger.this.singleThreadService.execute(new Runnable()
            {
              public void run()
              {
                try
                {
                  File localFile = FileLogger.this.getLogRoot();
                  if ((localFile == null) || (!FileLogger.this.getLogRoot().exists()))
                    return;
                  FileLogger.this.spaceAvailable = FileLogger.this.freeSpace();
                }
                catch (NullPointerException localNullPointerException)
                {
                  localNullPointerException.printStackTrace();
                  Log.e("FileLogger", localNullPointerException.getMessage());
                }
                catch (Exception localException)
                {
                  localException.printStackTrace();
                  Log.e("FileLogger", localException.getMessage());
                }
              }
            });
          }
        };
        this.timer.schedule(local3, 1200000L, 1200000L);
      }
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     com.easemob.util.FileLogger
 * JD-Core Version:    0.6.1
 */